<template>
  <div class="wang-editor">
    <div ref="editorContainer" class="editor-container"></div>
  </div>
</template>


<script>
import { upload } from "@/api/index";
import WangEditorLib from 'wangeditor';

export default {
  name: 'WangEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    height: {
      type: Number,
      default: 400
    },
    placeholder: {
      type: String,
      default: '请输入内容...'
    },
    readOnly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editor: null,
      isReady: false
    }
  },
  watch: {
    value: {
      handler(val) {
        if (this.isReady && this.editor && val !== this.editor.txt.html()) {
          this.editor.txt.html(val)
        }
      },
      deep: true
    }
  },
  mounted() {
    // 直接使用本地 import 的 WangEditor
    if (WangEditorLib) {
      window.wangEditor = WangEditorLib;
      this.initEditor();
    } else {
      // 本地引入失败则回退到CDN
      this.loadScript('https://cdn.jsdelivr.net/npm/wangeditor@4.7.15/dist/wangEditor.min.js', () => {
        this.loadCss('https://cdn.jsdelivr.net/npm/wangeditor@4.7.15/dist/css/wangEditor.min.css')
        this.initEditor()
      })
    }
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy()
      this.editor = null
    }
  },
  methods: {
    // 获取编辑器内容的方法
    getContent() {
      if (this.editor) {
        return this.editor.txt.html();
      }
      return '';
    },
    // 获取纯文本内容
    getText() {
      if (this.editor) {
        return this.editor.txt.text();
      }
      return '';
    },
    loadScript(url, callback) {
      const script = document.createElement('script')
      script.src = url
      script.onload = callback
      document.head.appendChild(script)
    },
    loadCss(url) {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      document.head.appendChild(link)
    },
    initEditor() {
      if (!window.wangEditor) {
        console.error('wangEditor 未加载')
        return
      }

      const E = window.wangEditor
      this.editor = new E(this.$refs.editorContainer)

      // 配置编辑器
      this.editor.config.height = this.height
      this.editor.config.placeholder = this.placeholder
      this.editor.config.zIndex = 100
      
      // 如果是只读模式，禁用编辑器
      if (this.readOnly) {
        this.editor.config.readOnly = true
      }

      // 配置菜单
      this.editor.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'justify',
        'quote',
        'emoticon',
        'image',
        'video',
        'table',
        'code',
        'splitLine',
        'undo',
        'redo'
      ]

      // 配置图片上传
      this.editor.config.uploadImgMaxSize = 5 * 1024 * 1024 // 5MB
      this.editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'webp']

      // 自定义图片上传
      this.editor.config.customUploadImg = async (files, insertImgFn) => {
        if (!files || !files.length) return

        try {
          const file = files[0]
          const formData = new FormData()
          formData.append('file', file)

          const res = await upload(formData)

          if (res.data) {
            // 上传成功，插入图片
            insertImgFn(res.data)
          } else {
            console.error('上传图片失败', res)
            this.$message && this.$message.error('上传图片失败')
          }
        } catch (error) {
          console.error('上传图片错误', error)
          this.$message && this.$message.error('上传图片出错')
        }
      }

      // 配置视频上传
      this.editor.config.uploadVideoMaxSize = 50 * 1024 * 1024 // 50MB
      this.editor.config.uploadVideoAccept = ['mp4', 'webm']

      // 自定义视频上传
      this.editor.config.customUploadVideo = async (files, insertVideoFn) => {
        if (!files || !files.length) return

        try {
          const file = files[0]
          const formData = new FormData()
          formData.append('file', file)

          const res = await upload(formData)

          if (res.data) {
            // 上传成功，插入视频
            insertVideoFn(res.data)
          } else {
            console.error('上传视频失败', res)
            this.$message && this.$message.error('上传视频失败')
          }
        } catch (error) {
          console.error('上传视频错误', error)
          this.$message && this.$message.error('上传视频出错')
        }
      }

      // 监听内容变化
      this.editor.config.onchange = () => {
        // 只读模式不触发变化事件
        if (!this.readOnly) {
          const html = this.editor.txt.html()
          this.$emit('input', html)
        }
      }

      // 创建编辑器
      this.editor.create()

      // 设置初始内容
      if (this.value) {
        this.editor.txt.html(this.value)
      }

      this.isReady = true
    }
  }
}
</script>

<style scoped>
.wang-editor {
  z-index: 100;
}

.editor-container {
  min-height: 300px;
}
</style>